package com.huidz.calendar.activity;

import android.app.ActivityOptions;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.transition.Slide;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.huidz.calendar.R;
import com.huidz.calendar.mainfragment.RemindFragment;
import com.huidz.calendar.model.UserModel;
import com.huidz.calendar.util.Apiutils;
import com.huidz.calendar.util.AppManager;
import com.huidz.calendar.util.Url;

import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class User_LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView byorzy;
    private int passwordtype = 0;//默认情况下密码不显示明文
    private EditText edit_password, edit_phone, edit_phone_num;

    private String phonestr, passwordstr;

    private int submit = 0, soup = 0;

    private RelativeLayout submit_user, get_soupt;
    private ImageView comeback;

    private TextView phone_num_login, remenber_login, test_text, pwd_login_text, luck_title_text;

    private LinearLayout phone_login, pwd_login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Slide slide = new Slide(Gravity.BOTTOM);
        slide.setDuration(200L);//间歇时间
        getWindow().setEnterTransition(slide);
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_userlogin);
        inti();
    }

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        comeback = findViewById(R.id.title_comeback);
        comeback.setOnClickListener(this);
        edit_phone_num = findViewById(R.id.edit_phone_num);
        pwd_login_text = findViewById(R.id.pwd_login_text);
        pwd_login_text.setOnClickListener(this);
        byorzy = findViewById(R.id.byorzy);
        byorzy.setOnClickListener(this);
        edit_password = findViewById(R.id.edit_password);
        edit_phone = findViewById(R.id.edit_phone);
        submit_user = findViewById(R.id.submit_user);
        phone_num_login = findViewById(R.id.phone_num_login);
        phone_num_login.setOnClickListener(this);
        get_soupt = findViewById(R.id.get_soupt);
        get_soupt.setOnClickListener(this);
        remenber_login = findViewById(R.id.remenber_login);
        remenber_login.setOnClickListener(this);
        submit_user.setOnClickListener(this);
        phone_login = findViewById(R.id.phone_login);
        pwd_login = findViewById(R.id.pwd_login);
        luck_title_text = findViewById(R.id.luck_title_text);
        luck_title_text.setOnClickListener(this);
        test_text = findViewById(R.id.test_text);
        SpannableString spanStrStart = new SpannableString("登录代表您已同意本App");
        SpannableString spanStrClick = new SpannableString("用户协议");
        spanStrClick.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent yhxy = new Intent(User_LoginActivity.this, FuWuTiaoKuanActivity.class);
                yhxy.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10000.html");
                yhxy.putExtra("title", "用户协议");
                startActivity(yhxy);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.RED); //设置颜色
                //去掉下划线，默认是带下划线的
                ds.setUnderlineText(false);
                //设置字体背景
//				ds.bgColor = Color.parseColor("#FF0000");
            }
        }, 0, spanStrClick.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        SpannableString spanStrEnd = new SpannableString("及");
        SpannableString spanStrEnds = new SpannableString("隐私政策");
        spanStrEnds.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent yszc = new Intent(User_LoginActivity.this, FuWuTiaoKuanActivity.class);
                yszc.putExtra("url", "http://web.xuekaixin.cn/article/show/id/10001.html");
                yszc.putExtra("title", "隐私政策");
                startActivity(yszc);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.RED); //设置颜色
                //去掉下划线，默认是带下划线的
                ds.setUnderlineText(false);
                //设置字体背景
//				ds.bgColor = Color.parseColor("#FF0000");
            }
        }, 0, spanStrClick.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        test_text.append(spanStrStart);
        test_text.append(spanStrClick);
        test_text.append(spanStrEnd);
        test_text.append(spanStrEnds);
        test_text.setMovementMethod(LinkMovementMethod.getInstance());
        edit_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!charSequence.toString().equals("")) {
                    submit_user.setBackgroundResource(R.drawable.rela_selected_bg_red);
                    submit = 1;
                } else {
                    submit_user.setBackgroundResource(R.drawable.rela_selected_bg_huise);
                    submit = 0;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        edit_phone_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!charSequence.toString().equals("")) {
                    get_soupt.setBackgroundResource(R.drawable.rela_selected_bg_red);
                    soup = 1;
                } else {
                    get_soupt.setBackgroundResource(R.drawable.rela_selected_bg_huise);
                    soup = 0;
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        edit_password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_DONE) {
                }
                return false;
            }
        });
        edit_phone_num.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_DONE) {
                    if (!edit_phone_num.getText().equals("")) {
                        Intent intent = new Intent(User_LoginActivity.this, GetCodeActivity.class);
                        intent.putExtra("phonenum", edit_phone_num.getText().toString());
                        startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(User_LoginActivity.this).toBundle());
                    }
                }
                return false;
            }
        });
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.title_comeback:
                onBackPressed();
                break;
            case R.id.byorzy:
                SetEdPassWord();
                break;
            case R.id.submit_user:
                if (submit == 1) {
                    Apiutils.windows(User_LoginActivity.this, submit_user, "正在登录");
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            Apiutils.closepopup();
                        }
                    }, 10000);
                    phonestr = edit_phone.getText().toString();
                    passwordstr = edit_password.getText().toString();
                    okHttp_postFromParameters();
                }
                break;
            case R.id.phone_num_login:
                phone_login.setVisibility(View.VISIBLE);
                pwd_login.setVisibility(View.GONE);
                luck_title_text.setVisibility(View.GONE);
                break;
            case R.id.remenber_login:
                Intent gtuser = new Intent(User_LoginActivity.this, Get_UserNameActivity.class);
                startActivity(gtuser, ActivityOptions.makeSceneTransitionAnimation(User_LoginActivity.this).toBundle());
                break;
            case R.id.pwd_login_text:
                phone_login.setVisibility(View.GONE);
                pwd_login.setVisibility(View.VISIBLE);
                luck_title_text.setVisibility(View.VISIBLE);
                break;
            case R.id.luck_title_text:
                Intent toxdw = new Intent(User_LoginActivity.this, User_ZhuceActivity.class);
                startActivity(toxdw, ActivityOptions.makeSceneTransitionAnimation(User_LoginActivity.this).toBundle());
                break;
            case R.id.get_soupt:
                if (soup == 1) {
                    if (!edit_phone_num.getText().equals("") && edit_phone_num.getText().toString().length() >= 11) {
                        Intent intent = new Intent(User_LoginActivity.this, GetCodeActivity.class);
                        intent.putExtra("phonenum", edit_phone_num.getText().toString());
                        startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(User_LoginActivity.this).toBundle());
                    } else {
                        Apiutils.SetToast(User_LoginActivity.this, "手机号输入有误");
                    }
                }
                break;


        }
    }

    public void SetEdPassWord() {
        switch (passwordtype) {
            case 0:
                passwordtype++;
                edit_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                break;

            case 1:
                passwordtype--;
                edit_password.setInputType((InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
                break;
        }
    }


    public void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("mobile", phonestr).add("password", passwordstr)
                            .build();
                    Request request = new Request.Builder().url(Url.LOGIN).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;
    public UserModel userm;
    public Handler gethot = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        userm = gson.fromJson(msg.obj.toString(),
                                UserModel.class);
                        mSharedPreferences = getSharedPreferences("user", MODE_PRIVATE);  //名称和类型
                        mEditor = mSharedPreferences.edit();
                        mEditor.putString("user_token", userm.getData().getLogintoken());
                        Url.USER_TOKEN = userm.getData().getLogintoken();
                        mEditor.putString("user_name", userm.getData().getNickname());
                        Url.USER_NAME = userm.getData().getNickname();
                        mEditor.putString("user_mobile", userm.getData().getMobile());
                        Url.USER_MOBILE = userm.getData().getMobile();
                        mEditor.putString("user_head", userm.getData().getAvatar());
                        Url.USER_HEAD = userm.getData().getAvatar();
                        mEditor.putString("user_id", userm.getData().getUserid());
                        Url.USER_ID = userm.getData().getUserid();
//                        mEditor.putString("user_wechat", userm.getData().getUser_wechat());
//                        Url.USER_WECHAT_NAME = userm.getData().getUser_name();
//                        mEditor.putString("user_wechatpwd", userm.getData().getUser_wechatpwd());
//                        mEditor.putString("user_zfb_zh", userm.getData().getUser_zfb_zh());
//                        Url.USER_ALIPAY_NAME = userm.getData().getUser_name();
//                        mEditor.putString("user_zfb_name", userm.getData().getUser_zfb_name());
//                        Url.USER_ALIPAY_USER_NAME = userm.getData().getUser_name();
//                        mEditor.putString("user_nickname", userm.getData().getUser_nickname());
//                        Url.USER_NICK_NAME = userm.getData().getUser_name();
//                        mEditor.putString("user_head", userm.getData().getUser_head());
//                        Url.USER_HEAD_IMG = userm.getData().getUser_head();
                        mEditor.apply();
                        mEditor.commit();
                        RemindFragment.shuaxing=true;
                        onBackPressed();
                    } else {
                        Apiutils.closepopup();
                        Apiutils.SetToast(User_LoginActivity.this, msgs + "");
                    }
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

}
